<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Gallery extends CI_Controller 
{
	protected $num_lang ;
	// congig hinh anh
	protected $table = 'tbl_gallery';
	protected $width = 1000;
	protected $height = 800;
	protected $size = 800;
	protected $type ='gif|jpg|png';
	protected $patch = './upload/gallery/';
	protected $name_link = "gallery";
	function __construct()
	{
		parent::__construct();
		$this->load->helper('login_helper');
		$this->load->model('Mgallery_cat');
		$this->load->model('Mgallery');
		$this->load->model('Msetting');
		$this->num_lang = $this->Msetting->get_lang();
    	//load libraries
    	$this->load->library('pagination');
		load_lang("admin");
    	$this->load->library('form_validation');
		session_start();
		if ( !isset($_SESSION['row_number']))
			$_SESSION['row_number']= 12;
		if ( !isset($_SESSION['gallery_cat']))
			$_SESSION['gallery_cat']= 0;
		check_login();
	}
	function index($catID='',$page='')
	{
		$limit =10;// $_SESSION['row_number'];
		$sub_id = $_SESSION['gallery_cat'] ;
		$config['base_url'] = site_url().'/admin/'.$this->name_link.'/index/';
		$config['first_link'] = 'First';
		$config['last_link'] = 'Last';
		$config['next_link'] = '&gt;&gt;';
		$config['prev_link'] = '&lt;&lt;';
		$config['cur_tag_open'] = '<a href="#" class="current">';
		$config['cur_tag_close'] = '</a>';
		$config['uri_segment'] = 4;
		$config['num_links'] = 2;
		$config['total_rows'] = $this->Mgallery->count_all($catID,'tbl_gallery');
		$config['per_page'] = $limit;
		$this->pagination->initialize($config);
    	if (empty($page))	$page = 0; //default value
   		$data['result'] = $this->Mgallery->list_data($catID,$page,$limit);
		$data['name_cat'] = $this->Mgallery->namecat($catID);
		$data['catID'] = $catID;
    	$data['page'] = str_replace('&nbsp;', '', $this->pagination->create_links());
    	$data['main'] = 'gallery_review';
    	$this->load->view('admin/layout/template_main', $data);
	}
	function create($catID='')
	{	
		if ($this->input->post('create'))
    	{
			if($this->num_lang >1)
   				$this->form_validation->set_rules('title_en', 'Tên tiếng Anh', 'required');
     		 $this->form_validation->set_rules('title_vi', 'Tên Tiếng việt', 'required');
    		 $this->form_validation->set_rules('price', 'Giá Sản phẩm', 'numeric|min_length[4]|max_length[15]');
 			 $this->form_validation->set_rules('cate', 'Loại dịch vụ', 'greater_than[0]');
			 $upload_img = $this->upload_file();
			 if(!$upload_img)
			 {
				$data['missing']['img']= $this->upload->display_errors() ." Width <= ".$this->width.", Height <= ".$this->height.", Size <= ".$this->size ;		 
			 }
			 else
			 {
				if ($this->form_validation->run() == false )
					$data['missing'] = $this->form_validation->_error_array; 
				else
				{
					if ($this->form_validation->run() && $this->sub_create($catID) )
					{

						echo "<script>";
						echo "alert('Tạo mới thành công');";
						echo "window.location='".base_url()."/index.php/admin/$this->name_link/index/".$catID."'";
						echo "</script>";
    
					}
     				else
        				$data['missing'] = $this->form_validation->_error_array;
				}
				
			 }
		}
    	elseif ($this->input->post('close'))
			redirect("admin/$this->name_link/index/".$catID,'refresh');
		$data['num_lang'] = $this->num_lang;	
		$data['main'] = 'gallery_create';
		$data['manu'] =  $this->Mgallery->get_manu(1);
		$data['namecat'] = $this->Mgallery->namecat($catID);
		$data['cate'] = $this->Mgallery->get_sub_cat(1);
		$data['title']='Thêm sản phẩm';
		$this->load->view('admin/layout/template_main', $data);		
	}
	//proccess add produ
	function sub_create($catID = "")
	{
		if(isset($_POST["create"]))
		{
			$status = $this->input->post("status");
			$cat = $this->input->post("cate");
			if($this->input->post('new') != "")
				$chk =1;
			else
			 	$chk = 0;
			$modify = time();
			$data = array(
							'gallery_lang' => 1,
							"gallery_name" =>htmlentities($this->input->post("title_vi"),ENT_QUOTES,"UTF-8"),
							"gallery_price"=>htmlentities($this->input->post("price"),ENT_QUOTES,"UTF-8"),
							"gallery_cate"=>$catID,
							"gallery_content" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
							"gallery_modify"=> $modify,
							'gallery_status'=>$status ,
							'gallery_new'=>$chk ,
							"gallery_code"=>htmlentities($this->input->post("gallery_code"),ENT_QUOTES,"UTF-8"),
							"gallery_image" =>  $_POST['img'],
							
						);		
			
			if($this->Mgallery->insert_gallery($data))
				return true;
			else
				return false;
		}
		else
			return false;
	}
	function update($catID,$id)
	{
		if ($this->input->post('update'))
    	{
			if($this->num_lang >1)
      			$this->form_validation->set_rules('title_en', 'Title English', 'required');

      		$this->form_validation->set_rules('title_vi', 'Title Vietnamese', 'required');
 			$this->form_validation->set_rules('price', 'Giá Sản phẩm', 'numeric|min_length[4]|max_length[15]');
			$file = $this->Mgallery->info_from_id($id,'tbl_gallery'); // lay du lieu de xoa va xet hinh anh ton tai 
			if(!empty($file))
				$file_name = $file[0]['gallery_image'];
			else
				$file_name = "";
			$test_img = $this->upload_file($file_name);
			if(!$test_img)
				$data['missing']['img']= $this->upload->display_errors() ." Width <= ".$this->width.", Height <= ".$this->height.", Size <= ".$this->size ;
			else
			{
				if ($this->form_validation->run() == false )
					$data['missing'] = $this->form_validation->_error_array;
				else
				{
					if( $_FILES['img']['error'] != 4 )
					{
						
						$path = $this->patch.$file[0]['gallery_image'];
						@unlink($path);
					}
					if($this->gallery_update_pro($catID,$id))
      				{
						echo "<script>";
						echo "alert('Cập nhật thành công');";
						echo "window.location='".base_url()."/index.php/admin/$this->name_link/update/".$catID."/".$id."'";
						echo "</script>";
					}
				}
			}
    	}
    	elseif ($this->input->post('close'))
			redirect("admin/$this->name_link/index/".$catID,'refresh');
		$data['num_lang'] = $this->num_lang;
		$data['catID'] = $catID;
		$data['main'] = 'gallery_update';
		$data['result'] = $this->Mgallery->info_from_id($id,'tbl_gallery');
		$data['namecat'] =$this->Mgallery->namecat($catID);	
		$this->load->view('admin/layout/template_main', $data);
	}
	function gallery_update_pro($catID,$id)
	{
		if(isset($_POST["update"]))
		{		
			if($this->input->post('new') != "")
				$chk =1;
			else $chk = 0;
			$status = $this->input->post("status");
			$modify = time();
			$data = array(
							"gallery_name" =>htmlentities($this->input->post("title_vi"),ENT_QUOTES,"UTF-8"),
							"gallery_price"=>htmlentities($this->input->post("price"),ENT_QUOTES,"UTF-8"),
							"gallery_content" => htmlentities($this->input->post("direction_vi"),ENT_QUOTES,"UTF-8"),
							'gallery_new'=>$chk ,
							"gallery_code"=>htmlentities($this->input->post("gallery_code"),ENT_QUOTES,"UTF-8"),
							"gallery_modify"=> $modify,
							'gallery_status'=>$status,
							"gallery_image" => $_POST['img'],
						);
			if($this->Mgallery->update_gallery($data,$id))
				return true;
			else
				return false;
		}
		else
			return false;
	}
	function request($id = '')
	{
		$require = array('show', 'delete','sub_cat');
		foreach ($_POST as $key=>$value)
			if (in_array($key, $require))
				$act = $key;
		if (! empty($act))
		{
			switch ($act)
			{
				case 'show': 
					$_SESSION['row_number'] = $this->input->post('row_number');
					break;
				case 'sub_cat': //show
					$_SESSION['gallery_cat'] = $this->input->post('sub_cat');
					 break;
				case 'delete': //delete
					$this->Mgallery->delete();
					break;
			}//end switch
			redirect('admin/gallery', 'refresh');
		}//end if
	}
	public function delete($catID,$id)
	{
		if($id > 0 )
		{
			$file = $this->Mgallery->info_from_id($id,'tbl_gallery');
			if (!empty($file[0]['gallery_image']))
			{
				$path = $this->patch.$file[0]['gallery_image'];				
				@unlink($path);
			}
			$this->Mgallery->del_item($id);
		}
		redirect('admin/'.$this->name_link.'/index/'.$catID, 'refresh');
	}
 	function upload_file($file="",$input_file = 'img')
 	{
	 	$_POST['img'] = $file;
    	if ($_FILES[$input_file]['error'] == 0  )
    	{
      		$path_directory = $this->patch;
      		if ( ! is_dir($path_directory))
				mkdir($path_directory);
      		$config['upload_path'] = $path_directory;
			$config['allowed_types'] = $this->type;
			$config['max_size'] = $this->size;
			$config['max_width'] = $this->width;
			$config['max_height'] = $this->height;
      		$this->load->library('upload',$config);
      		if ($this->upload->do_upload($input_file))
      		{
        		$info_file = $this->upload->data();
        		$file_path = $info_file['file_name'];
      			$_POST['img'] = $file_path;
      		}
	 		else
	  		{
		  		return false;
	  		}
    	}
		return true;
  	}
  	public function del_image($catID,$id)
 	{
		$data = $this->Mgallery->info_detail($id,$this->table);
		if($data != "")
		{
			$set = array('gallery_image' => "");
			$path = $this->patch."/".$data['gallery_image'];
			if(@file_exists($path))
				@unlink($path);
			$this->Mgallery->update_gallery($set,$id);
			echo "<script> alert('Xóa hình thành công');window.location='".base_url()."/index.php/admin/$this->name_link/update/".$catID."/".$id."'</script>";
		}
	}
}
?>
